import os
import smtplib
from email.mime.text import MIMEText
from email.header import Header
import configparser
import logging
from logging.config import fileConfig

cfgdir = os.path.split(os.path.realpath(__file__))[0]
print(cfgdir)
cfg = os.path.join(cfgdir,'logging_config.ini')
# fileConfig("logging_config.ini", disable_existing_loggers=False)
logger = logging.getLogger('simple_example')

class emailUtils(object):
    smtp = None
    user = None
    password = None
    def __init__(self, cfg):
        self.config = None
        config = configparser.ConfigParser()
        if cfg:
            config.read(cfg)
        else:
            cfgdir = os.path.split(os.path.realpath(__file__))[0]
            print(cfgdir)
            paths = cfgdir.split("/")
            a = len(paths) - 2
            separator = '/'
            arr = paths[1:a]
            b = '/' + separator.join(arr) + '/'
            cfg = os.path.join(b, 'config.cfg')
            config.read(cfg)
        emailUtils.smtp = config.get('mail', 'smtp')
        emailUtils.user = config.get('mail', 'user')
        emailUtils.password = config.get('mail', 'password')

    @staticmethod
    def simplysend(receiver=None, title="", content=""):
        smtpObj = None;
        if receiver is None:
            receiver = []
        logging.info('')
        try:
            logging.info(receiver)
            # 邮件内容
            message = MIMEText(content, 'plain', 'utf-8')
            message['From'] = "{0}<{1}>".format("A4", emailUtils.user)
            message['To'] = ', '.join(receiver)
            message['Subject'] = Header(title, 'utf-8')
            smtpObj = smtplib.SMTP()
            smtpObj.connect(emailUtils.smtp, 25)  # 25 为 SMTP 端口号
            smtpObj.login(emailUtils.user, emailUtils.password)
            smtpObj.sendmail(emailUtils.user, receiver, message.as_string())

            # 获取图片
            # with open("D:\\testdata\\apic41419_s.jpg", 'rb') as fp:
            #    msgImage = MIMEImage(fp.read())
            # message.attach(msgImage)
        except smtplib.SMTPException as e:
            print("Error: 无法发送邮件", e)
        finally:
            print("\n")
            smtpObj.quit()
            smtpObj.close()

    @staticmethod
    def attachedsend(self,receiver=[],title="",content="",attachment=[]):
        logging.info('')
        smtpObj = None
        try:
            logging.info(receiver)
        except smtplib.SMTPException as e:
            print("Error: 无法发送邮件", e)
        finally:
            smtpObj.quit()
            smtpObj.close()
if __name__ == "__main__":
    a = emailUtils(cfg=None)
    a.simplysend(receiver=['a467241@dingtalk.com','liuchuang@9tts.cn'],title='测试',content="test message")